import { Injectable } from '@nestjs/common'
import { Dayjs } from 'dayjs'
import { parseDateInChina } from 'src/common/time-helper'

// 808 协议解析出的数据
export interface I808ProtocolData {
    /** 通信时间 */
    receivedTime: string | null
    /** ICCID */
    iccid: string | null
    /** 车辆状态 解锁 启动 锁车 */
    vehicleStatus: string | null
    /** 电门状态 0 1 */
    doorStatus: string | null
    //蓝牙是否开启
    isBlueToothEnabled: boolean | null
    //蓝牙是否连接
    isBlueToothConnected: boolean | null
    //车轮移动
    isWheelMotion: boolean | null
    //继电器
    isAcc: boolean | null
    //通信信号
    cellularSignal: number | null
    //定位时间
    reportTime: string | null
    /** 电压 */
    voltage: number | null
    /** 超速报警 */
    overSpeedAlarm: boolean | null
    /** 低压报警 */
    lowPressureAlarm: boolean | null
    /** 防盗报警 */
    theftAlarm: boolean | null
    /** 是否定位*/
    isLocated: boolean | null
    /** 纬度 */
    latitude: number | null
    /** 经度 */
    longitude: number | null
    /** 高度 */
    height: number | null
    /** 速度 */
    speed: number | null
    /** 方向 */
    direction: number | null
    /** 定位时间 */
    locationTime: string | null
    /** 定位卫星数量 */
    satelliteSignal: number | null
    // wifi基站信息
    wifiStations: { mac: string; signal: number }[] | null
    // lbs基站信息
    lbsStations: { mcc: number; mnc: number; lac: number; cellId: number; signal: number }[] | null
    /** 卫星定位数据 */
    satelliteData: { count: number; signal: number[] } | null
    /** 4G卫星定位数据 */
    fourGSatelliteData: { count: number; signal: number[] } | null
}

// 附加消息ID
const ExtraMessageId = {
    // 无线通信网络强度
    WIFI_STRENGTH: '30',
    // 定位卫星数量
    SATELLITE_SIGNAL: '31',
    // Wi-Fi 数据
    WIFI_DATA: '54',
    // 基站数据
    LBS_DATA: '5D',
    // 防盗报警
    THEFT_ALARM: '61',
    // 电压
    VOLTAGE: '62',
    // 车辆状态
    DEVICE_STATUS: '66',
    // 外设状态
    EXTERNAL_DEVICE_STATUS: '67',
    // GPS 卫星数据 2G
    SATELLITE_DATA: '70',
    // 4G 卫星数据
    FOUR_G_SATELLITE_DATA: '72'
}

// 主要消息类型
const MessageType = {
    /** 终端心跳 */
    HEARTBEAT: '0002',
    /** 位置信息汇报 */
    LOCATION: '0200',
    /** 数据上行透传 */
    DATA_UP_TRANSPARENT: '0900',
    /** 终端属性应答 */
    TERMINAL_PROPERTY_RESPONSE: '0107'
}

@Injectable()
export class Protocol808Service {
    // 缓存默认数据模板，避免重复创建
    private readonly defaultLocationTemplate: I808ProtocolData = {
        receivedTime: null,
        iccid: null,
        vehicleStatus: null,
        doorStatus: null,
        isBlueToothEnabled: null,
        isBlueToothConnected: null,
        isWheelMotion: null,
        isAcc: null,
        cellularSignal: null,
        reportTime: null,
        voltage: null,
        overSpeedAlarm: null,
        lowPressureAlarm: null,
        theftAlarm: null,
        isLocated: null,
        latitude: null,
        longitude: null,
        height: null,
        speed: null,
        direction: null,
        locationTime: null,
        satelliteSignal: null,
        wifiStations: null,
        lbsStations: null,
        satelliteData: null,
        fourGSatelliteData: null
    }

    constructor() {}

    // 构建一个默认的808协议的设备数据 - 优化版本
    private buildDefaultDeviceData(): I808ProtocolData {
        return {
            ...this.defaultLocationTemplate
        }
    }

    /**
     * 只合并非null值，保留现有有效数据
     */
    private mergeProtocolData(target: I808ProtocolData, source: I808ProtocolData): I808ProtocolData {
        const result = { ...target }

        // 遍历源对象的所有属性，只合并非null值
        for (const key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                const sourceValue = source[key]
                if (sourceValue !== null && sourceValue !== undefined) {
                    result[key] = sourceValue
                }
            }
        }

        return result
    }

    // 批量解析数据 将结果进行合并
    parseBatch(deviceRawDataList: string[], messageTypeFilter?: string[]): I808ProtocolData {
        if (deviceRawDataList.length === 0) {
            return this.buildDefaultDeviceData()
        }

        // 如果指定了消息类型过滤器，先过滤数据
        let filteredDataList = deviceRawDataList
        if (messageTypeFilter && messageTypeFilter.length > 0) {
            filteredDataList = deviceRawDataList.filter(rawData => this.isValidMessageType(rawData, messageTypeFilter))

            if (filteredDataList.length === 0) {
                return this.buildDefaultDeviceData()
            }
        }

        // 使用第一条数据作为基础，避免多次 Object.assign
        let mergedData = this.parseCore(filteredDataList[0])

        // 如果只有一条数据，直接返回
        if (filteredDataList.length === 1) {
            return mergedData
        }

        // 对于多条数据，进行智能合并
        for (let i = 1; i < filteredDataList.length; i++) {
            const currentData = this.parseCore(filteredDataList[i])
            mergedData = this.mergeProtocolData(mergedData, currentData)
        }

        return mergedData
    }

    /**
     * 检查原始数据是否符合指定的消息类型
     */
    private isValidMessageType(deviceRawData: string, messageTypeFilter: string[]): boolean {
        // 预先分割数据，获取消息数据部分
        const spaceIndex1 = deviceRawData.indexOf(' ')
        const spaceIndex2 = deviceRawData.indexOf(' ', spaceIndex1 + 1)

        // 如果数据格式不符合，返回false
        if (spaceIndex1 === -1 || spaceIndex2 === -1) {
            return false
        }

        // 检查方向是否为上行（Rx）
        const direction = deviceRawData.substring(spaceIndex1 + 1, spaceIndex2)
        if (direction !== 'Rx') {
            return false
        }

        const messageDataStart = spaceIndex2 + 1
        if (messageDataStart >= deviceRawData.length) {
            return false
        }

        // 检查消息类型
        for (const type of messageTypeFilter) {
            if (deviceRawData.length >= messageDataStart + type.length) {
                let matches = true
                for (let m = 0; m < type.length; m++) {
                    if (deviceRawData[messageDataStart + m] !== type[m]) {
                        matches = false
                        break
                    }
                }
                if (matches) {
                    return true
                }
            }
        }

        return false
    }

    /**
     * 解析808协议设备数据
     */
    parseCore(deviceRawData: string): I808ProtocolData {
        // 预先分割数据，避免重复分割
        const spaceIndex1 = deviceRawData.indexOf(' ')
        const spaceIndex2 = deviceRawData.indexOf(' ', spaceIndex1 + 1)

        // 如果数据格式不符合 直接返回空对象
        if (spaceIndex1 === -1 || spaceIndex2 === -1) {
            return this.buildDefaultDeviceData()
        }

        const timeStr = deviceRawData.substring(0, spaceIndex1)
        const messageData = deviceRawData.substring(spaceIndex2 + 1)

        // 根据808协议 接受的消息我们需要转义还原数据
        const unescapedData = this.unescapeDataOptimized(messageData)

        // 提取消息ID进行类型识别
        const messageId = this.extractMessageId(unescapedData)

        // 根据消息类型分发到不同的解析方法
        const result = this.buildDefaultDeviceData()
        result.receivedTime = this.getTimeISOString(timeStr)

        switch (messageId) {
            case MessageType.LOCATION:
                return this.parseLocationMessage(unescapedData, result)
            case MessageType.HEARTBEAT:
                return this.parseHeartbeatMessage(unescapedData, result)
            case MessageType.TERMINAL_PROPERTY_RESPONSE:
                return this.parseTerminalPropertyMessage(unescapedData, result)
            default:
                return this.parseUnknownMessage(unescapedData, result)
        }
    }

    /**
     * 提取消息ID
     */
    private extractMessageId(unescapedData: string): string {
        // 消息ID位于数据的第0-3位（2字节）
        if (unescapedData.length >= 4) {
            return unescapedData.substring(0, 4).toUpperCase()
        }
        return ''
    }

    /**
     * 解析位置信息汇报消息 (0x0200)
     */
    private parseLocationMessage(unescapedData: string, baseResult: I808ProtocolData): I808ProtocolData {
        // 去掉前面 消息ID 消息头 12 字节 和 最后两位 异或校验码
        const messageBody = unescapedData.slice(24, -2)

        // 位置基本信息 0-27 字节
        const location = this.parseLocationBasicInfoOptimized(messageBody.slice(0, 56))

        // 附加信息
        const extraInfo = this.parseExtraInfoOptimized(messageBody.slice(56))

        // 合并数据
        baseResult.overSpeedAlarm = location.overSpeedAlarm
        baseResult.lowPressureAlarm = location.lowPressureAlarm
        baseResult.isAcc = location.isAcc
        baseResult.isLocated = location.isLocated
        baseResult.latitude = location.latitude
        baseResult.longitude = location.longitude
        baseResult.height = location.height
        baseResult.speed = location.speed
        baseResult.direction = location.direction
        baseResult.locationTime = location.locationTime

        baseResult.voltage = extraInfo.voltage
        baseResult.theftAlarm = extraInfo.theftAlarm
        baseResult.cellularSignal = extraInfo.cellularSignal
        baseResult.wifiStations = extraInfo.wifiStations
        baseResult.satelliteData = extraInfo.satelliteData
        baseResult.fourGSatelliteData = extraInfo.fourGSatelliteData
        baseResult.satelliteSignal = extraInfo.satelliteSignal
        baseResult.lbsStations = extraInfo.lbsStations

        return baseResult
    }

    /**
     * 解析终端心跳消息 (0x0002)
     */
    private parseHeartbeatMessage(unescapedData: string, baseResult: I808ProtocolData): I808ProtocolData {
        // 心跳消息包
        // 内置电池电量百分比
        // 主电源电压和状态
        // 需要拿到电压
        // 通信信号强度
        // 去掉消息头(24字符)和校验码(2字符)，获取消息体
        if (unescapedData.length < 26) {
            console.warn('终端心跳消息数据长度不足')
            return baseResult
        }

        const messageBody = unescapedData.slice(24, -2)

        // 检查消息体长度是否足够进行解析（至少6个字符，3字节）
        if (messageBody.length < 6) {
            console.warn('心跳消息体长度不足，无法解析电压和信号强度')
            return baseResult
        }

        // 内置电池百分比 第0字节
        // const batteryPercentageMessage = messageBody.substring(0, 2) // 第1-2个字符（第0字节）
        // const batteryPercentage = this.parseHexFast(batteryPercentageMessage)

        // 主电源电压 第1-2字节
        // Bit0~bit11:主电源电压，单位：0.1V
        // 接线设备：外电电压
        // 无线设备：内置电池电压
        // Bit:12:内置电池充电状态，0-已插入充电，1-未插入充电
        // Bit13~bit15：保留备用
        // 例1：0x102A表示电压4.2V、未插入充电
        // 例2：0x0FFF表示电压409.5V、已插入充电
        const voltageMessage = messageBody.substring(2, 6) // 第3-6个字符（第1-2字节）
        const voltageRaw = this.parseHexFast(voltageMessage)

        // 提取Bit0~bit11的电压值（单位0.1V）
        const voltageValue = (voltageRaw & 0x0fff) / 10 // 取低12位并转换为实际电压
        baseResult.voltage = voltageValue

        // 信号强度 第3字节
        const cellularSignalMessage = messageBody.substring(6, 8) // 第7-8个字符（第3字节）
        const cellularSignalValue = this.parseHexFast(cellularSignalMessage)
        baseResult.cellularSignal = cellularSignalValue

        return baseResult
    }

    /**
     * 解析终端属性应答消息 (0x0107)
     */
    private parseTerminalPropertyMessage(unescapedData: string, baseResult: I808ProtocolData): I808ProtocolData {
        try {
            // 终端属性应答消息包含设备的基本属性信息
            // 示例数据: 0107005901207585886607B20000535A53585958595F4445564943455F5438303800000000000035383538383636898608331923C08975161758593830385F424F4F545F3230323430313232323033341258593830385F3230323430353136313433380000AB

            // 消息结构:
            // - 消息头: 12字节 (24个十六进制字符)
            // - 消息体: 从第13字节开始
            // - ICCID位置: 消息体第34字节开始，共10字节 BCD[10]

            // 去掉消息头(24字符)和校验码(2字符)，获取消息体
            if (unescapedData.length < 26) {
                console.warn('终端属性应答消息数据长度不足')
                return baseResult
            }

            const messageBody = unescapedData.slice(24, -2)

            // 验证消息体长度是否足够包含ICCID
            // ICCID位于消息体第34字节开始，共10字节 = 20个十六进制字符
            const iccidStartOffset = 34 * 2 // 字节转换为十六进制字符偏移
            const iccidLength = 10 * 2 // 10字节 = 20个十六进制字符

            if (messageBody.length < iccidStartOffset + iccidLength) {
                console.warn('终端属性应答消息体长度不足，无法提取ICCID')
                return baseResult
            }

            // 提取ICCID数据 (BCD[10]格式)
            const iccidHex = messageBody.substring(iccidStartOffset, iccidStartOffset + iccidLength)

            // 更新结果
            baseResult.iccid = iccidHex
        } catch (error) {
            console.error('解析终端属性应答消息时出错:', error)
        }

        return baseResult
    }

    /**
     * 解析未知类型消息
     */
    private parseUnknownMessage(unescapedData: string, baseResult: I808ProtocolData): I808ProtocolData {
        // 对于未知类型的消息，记录日志并返回基础数据

        return baseResult
    }

    /**
     * 获取时间ISO字符串
     */
    private getTimeISOString(timeStr: string): string | null {
        const timestamp = this.parseTimeToTimestamp(timeStr)
        if (timestamp === null) {
            return null
        }

        return new Date(timestamp).toISOString()
    }

    /**
     * 时间解析方法 - 返回时间戳
     */
    private parseTimeToTimestamp(rawTime: string): number | null {
        try {
            // 直接查找点的位置
            const dotIndex1 = rawTime.indexOf('.')
            const dotIndex2 = rawTime.lastIndexOf('.')

            if (dotIndex1 === -1 || dotIndex2 === -1 || dotIndex1 === dotIndex2) {
                return null
            }

            const date = rawTime.substring(0, dotIndex1)
            const time = rawTime.substring(dotIndex1 + 1, dotIndex2)
            const ms = rawTime.substring(dotIndex2 + 1)

            // 直接构建时间字符串
            const timeString = `${date} ${time.substring(0, 2)}:${time.substring(2, 4)}:${time.substring(4, 6)}.${ms}`

            return parseDateInChina(timeString).valueOf()
        } catch (error) {
            console.error(`格式化时间失败 808: ${rawTime},${error}`)
            return null
        }
    }

    /**
     * 优化的转义还原数据方法
     * 根据808协议规则：
     * - 7d02 -> 7e
     * - 7d01 -> 7d
     */
    private unescapeDataOptimized(data: string): string {
        // 预分配结果数组，避免字符串拼接
        const result: string[] = []
        let i = 0

        while (i < data.length) {
            if (i < data.length - 3) {
                const fourChars = data.substring(i, i + 4).toLowerCase()
                if (fourChars === '7d02') {
                    result.push('7e')
                    i += 4
                    continue
                } else if (fourChars === '7d01') {
                    result.push('7d')
                    i += 4
                    continue
                }
            }
            result.push(data[i])
            i++
        }

        return result.join('')
    }

    // 解析位置基本信息
    private parseLocationBasicInfoOptimized(rawData: string) {
        // 预先切片所有需要的数据段，减少重复的 slice 操作
        const alarmFlag = rawData.substring(0, 8)
        const status = rawData.substring(8, 16)
        const latitude = rawData.substring(16, 24)
        const longitude = rawData.substring(24, 32)
        const altitude = rawData.substring(32, 36)
        const speed = rawData.substring(36, 40)
        const direction = rawData.substring(40, 44)
        const time = rawData.substring(44)

        // 批量解析十六进制，减少函数调用
        const alarmValue = this.parseHexFast(alarmFlag)
        const statusValue = this.parseHexFast(status)
        const isNorth = (statusValue & 0x00000004) === 0
        const isEast = (statusValue & 0x00000008) === 0
        return {
            // 解析报警标志
            overSpeedAlarm: (alarmValue & 0x00000002) !== 0,
            lowPressureAlarm: (alarmValue & 0x00000080) !== 0,
            // 解析状态
            isAcc: (statusValue & 0x00000001) !== 0,
            isLocated: (statusValue & 0x00000002) !== 0,
            // 解析位置数据
            latitude: (this.parseHexFast(latitude) / 1000000) * (isNorth ? 1 : -1),
            longitude: (this.parseHexFast(longitude) / 1000000) * (isEast ? 1 : -1),
            height: this.parseHexFast(altitude),
            speed: this.parseHexFast(speed) / 10,
            direction: this.parseHexFast(direction),
            locationTime: this.parseTime(time)
        }
    }

    /**
     * 快速十六进制解析 - 避免parseInt的开销
     */
    private parseHexFast(hex: string): number {
        let result = 0
        for (let i = 0; i < hex.length; i++) {
            const char = hex[i]
            let digit: number

            if (char >= '0' && char <= '9') {
                digit = char.charCodeAt(0) - 48 // '0'.charCodeAt(0)
            } else if (char >= 'a' && char <= 'f') {
                digit = char.charCodeAt(0) - 87 // 'a'.charCodeAt(0) - 10
            } else if (char >= 'A' && char <= 'F') {
                digit = char.charCodeAt(0) - 55 // 'A'.charCodeAt(0) - 10
            } else {
                // 无效字符，回退到parseInt
                return parseInt(hex, 16)
            }

            result = result * 16 + digit
        }
        return result
    }

    // 解析附加信息
    private parseExtraInfoOptimized(extraInfo: string) {
        // 切割附加消息
        const messageList = this.cutExtraMessageOptimized(extraInfo)

        const result: Pick<
            I808ProtocolData,
            | 'cellularSignal'
            | 'theftAlarm'
            | 'satelliteSignal'
            | 'wifiStations'
            | 'lbsStations'
            | 'voltage'
            | 'satelliteData'
            | 'fourGSatelliteData'
        > = {
            // 通信信号
            cellularSignal: null,
            // 防盗报警
            theftAlarm: null,
            // 卫星信号 数量
            satelliteSignal: null,
            // wifi基站信息
            wifiStations: null,
            // lbs基站信息
            lbsStations: null,
            // 电压
            voltage: null,
            // 卫星定位数据
            satelliteData: null,
            // 4G卫星定位数据
            fourGSatelliteData: null
        }

        // 解析附加消息 - 优化版本
        for (const message of messageList) {
            const messageId = message.substring(0, 2)
            try {
                switch (messageId) {
                    case ExtraMessageId.WIFI_STRENGTH:
                        result.cellularSignal = this.parseWifiStrengthOptimized(message)
                        break
                    case ExtraMessageId.SATELLITE_SIGNAL:
                        result.satelliteSignal = this.parseSatelliteSignalOptimized(message)
                        break
                    case ExtraMessageId.WIFI_DATA:
                        result.wifiStations = this.parseWifiDataOptimized(message)
                        break
                    case ExtraMessageId.LBS_DATA:
                        result.lbsStations = this.parseLbsDataOptimized(message)
                        break
                    case ExtraMessageId.VOLTAGE:
                        result.voltage = this.parseVoltageOptimized(message)
                        break
                    case ExtraMessageId.SATELLITE_DATA:
                        result.satelliteData = this.parseSatelliteDataOptimized(message)
                        break
                    case ExtraMessageId.FOUR_G_SATELLITE_DATA:
                        result.fourGSatelliteData = this.parseFourGSatelliteDataOptimized(message)
                        break
                }
            } catch (error) {
                console.error(`解析消息ID ${messageId} 时出错:`, error)
            }
        }

        return result
    }

    private parseWifiStrengthOptimized(message: string): number {
        const data = message.substring(4)
        return this.parseHexFast(data)
    }

    private parseSatelliteSignalOptimized(message: string): number {
        const data = message.substring(4)
        return this.parseHexFast(data)
    }

    private parseVoltageOptimized(message: string): number {
        const data = message.substring(4)
        return this.parseHexFast(data) / 10
    }

    private parseWifiDataOptimized(message: string): I808ProtocolData['wifiStations'] {
        const data = message.substring(4)

        if (data.length < 2) {
            return null
        }

        const count = this.parseHexFast(data.substring(0, 2))
        const wifiData: { mac: string; signal: number }[] = []

        let offset = 2
        for (let i = 0; i < count && offset + 14 <= data.length; i++) {
            // MAC地址 6字节 = 12个字符
            const macHex = data.substring(offset, offset + 12)
            const mac = this.formatMacAddress(macHex)
            offset += 12
            // 信号强度 1字节 = 2个字符
            const signal = this.parseHexFast(data.substring(offset, offset + 2)) - 113
            offset += 2

            wifiData.push({ mac, signal })
        }

        return wifiData
    }

    private parseLbsDataOptimized(message: string): I808ProtocolData['lbsStations'] {
        const data = message.substring(4)

        if (data.length < 2) {
            return null
        }

        const count = this.parseHexFast(data.substring(0, 2))
        const lbsData: { mcc: number; mnc: number; lac: number; cellId: number; signal: number }[] = []

        let offset = 2
        for (let i = 0; i < count && offset + 20 <= data.length; i++) {
            const mcc = this.parseHexFast(data.substring(offset, offset + 4))
            offset += 4
            const mnc = this.parseHexFast(data.substring(offset, offset + 2))
            offset += 2
            const lac = this.parseHexFast(data.substring(offset, offset + 4))
            offset += 4
            const cellId = this.parseHexFast(data.substring(offset, offset + 8))
            offset += 8
            const signal = this.parseHexFast(data.substring(offset, offset + 2)) - 113
            offset += 2

            lbsData.push({ mcc, mnc, lac, cellId, signal })
        }

        return lbsData
    }

    private parseSatelliteDataOptimized(message: string): I808ProtocolData['satelliteData'] {
        // 消息长度不固定
        // 第一字节时GPS卫星数量 后面时信号CN值
        // 700709393838372901 表示 九颗星，信号CN为39 38 38 37 29 01
        // 700105表示有5个星，CN值都是0
        // 700100表示有0个星
        // 7001FF表示未开启GPS

        const data = message.substring(4) // 跳过消息ID和长度

        if (data.length < 2) {
            return null
        }

        // 读取卫星数量
        const count = this.parseHexFast(data.substring(0, 2))

        // 检查是否未开启GPS (FF标识)
        if (data.length >= 4 && data.substring(2, 4).toUpperCase() === 'FF') {
            return { count: 0, signal: [] }
        }

        // 解析信号CN值
        const signal: number[] = []
        let offset = 2

        for (let i = 0; i < count && offset + 2 <= data.length; i++) {
            const cnValue = this.parseHexFast(data.substring(offset, offset + 2))
            signal.push(cnValue)
            offset += 2
        }

        return { count, signal }
    }

    private parseFourGSatelliteDataOptimized(message: string): I808ProtocolData['fourGSatelliteData'] {
        // 消息体的前6字节时最后一次收到GPS时间 6字节
        // 后面一个字节是卫星总数 0f 表示15个星
        // 后面三字节是卫星CN值 最强的6个 每个字节的高四位和低四位表示一个卫星信号CN-25 低于26取0 大于40取F，不满6个补0
        // FFAA110 表示信号CN值为40 40 35 35 26 0

        const data = message.substring(4) // 跳过消息ID和长度

        // 验证数据长度：GPS时间(6字节) + 卫星总数(1字节) + CN值(3字节) = 10字节 = 20个字符
        if (data.length < 20) {
            return null
        }

        // 跳过前6字节的GPS时间，从第12个字符开始
        let offset = 12

        // 解析卫星总数
        const count = this.parseHexFast(data.substring(offset, offset + 2))
        offset += 2

        // 解析3字节的CN值数据
        const signal: number[] = []
        for (let i = 0; i < 3 && offset + 2 <= data.length; i++) {
            const byteValue = this.parseHexFast(data.substring(offset, offset + 2))

            // 提取高4位和低4位
            const highNibble = (byteValue >> 4) & 0x0f
            const lowNibble = byteValue & 0x0f

            // 转换为CN值：4位值 + 25，处理边界情况
            // 0 表示低于26，F 表示大于40
            if (highNibble !== 0) {
                const cnValue = highNibble === 0x0f ? 40 : Math.min(40, highNibble + 25)
                signal.push(cnValue)
            } else {
                signal.push(0)
            }

            if (lowNibble !== 0) {
                const cnValue = lowNibble === 0x0f ? 40 : Math.min(40, lowNibble + 25)
                signal.push(cnValue)
            } else {
                signal.push(0)
            }

            offset += 2
        }

        // 只返回实际的卫星数量对应的信号值，最多6个
        const actualSignal = signal.slice(0, Math.min(6, count))

        return { count, signal: actualSignal }
    }

    /**
     * 格式化MAC地址
     */
    private formatMacAddress(macHex: string): string {
        const result: string[] = []
        for (let i = 0; i < macHex.length; i += 2) {
            result.push(macHex.substring(i, i + 2))
        }
        return result.join(':')
    }

    //  切割附加消息
    private cutExtraMessageOptimized(extraInfo: string): string[] {
        const messageList: string[] = []

        if (!extraInfo || extraInfo.length === 0) {
            return messageList
        }

        let currentIndex = 0

        while (currentIndex < extraInfo.length) {
            // 确保至少有消息ID和消息长度
            if (currentIndex + 4 > extraInfo.length) {
                break
            }

            // 读取消息长度
            const lengthHex = extraInfo.substring(currentIndex + 2, currentIndex + 4)
            const messageLength = this.parseHexFast(lengthHex)

            // 消息体的字符数
            const messageBodyCharCount = messageLength * 2

            // 检查是否有足够的字符
            if (currentIndex + 4 + messageBodyCharCount > extraInfo.length) {
                break
            }

            // 组装完整的消息
            const completeMessage = extraInfo.substring(currentIndex, currentIndex + 4 + messageBodyCharCount)
            messageList.push(completeMessage)

            currentIndex += 4 + messageBodyCharCount
        }

        return messageList
    }

    /**
     * 时间解析方法
     */
    private parseTime(time: string): string {
        // 直接构建时间字符串，避免多次 slice 操作
        const year = '20' + time.substring(0, 2)
        const month = time.substring(2, 4)
        const day = time.substring(4, 6)
        const hour = time.substring(6, 8)
        const minute = time.substring(8, 10)
        const second = time.substring(10, 12)

        const timeString = `${year}-${month}-${day} ${hour}:${minute}:${second}`
        return parseDateInChina(timeString).toISOString()
    }

    /**
     * 时间格式化方法
     * @param rawTime 原始时间字符串
     * @returns 格式化后的Dayjs对象
     */
    private formatTimeOptimized(rawTime: string): Dayjs | null {
        const timestamp = this.parseTimeToTimestamp(rawTime)
        if (timestamp === null) {
            return null
        }
        return parseDateInChina(new Date(timestamp))
    }

    /**
     * 格式化时间 - 保留原方法以保持兼容性
     * @param rawTime 原始时间字符串
     * @returns 格式化后的Dayjs对象
     */
    formatTime(rawTime: string): Dayjs | null {
        return this.formatTimeOptimized(rawTime)
    }
}
